#!/bin/bash
set -e

# Generate key
chmod +x /usr/local/bin/gen.exp
/usr/local/bin/gen.exp
echo "Successfully generate key"

# Write the public key to the target server
chmod +x /usr/local/bin/ssh.exp
/usr/local/bin/ssh.exp
echo "Successfully write the public key to the target server"

# Determine whether the file exists
if [ -e "${JIANMU_FILE_PATH}" ]
    then
        ssh ${JIANMU_TARGET_SERVER_HOST} "mkdir -p ${JIANMU_TARGET_SERVER_DIR}"
        # Start distribution
        if [ -d "${JIANMU_FILE_PATH}" ]; then
            # if path is a dir
            rsync -av "${JIANMU_FILE_PATH}"/* -e "ssh -p ${JIANMU_SERVER_PORT}" ${JIANMU_TARGET_SERVER_HOST}:"${JIANMU_TARGET_SERVER_DIR}"
        else
            # if path is a file
            rsync -av "${JIANMU_FILE_PATH}" -e "ssh -p ${JIANMU_SERVER_PORT}" ${JIANMU_TARGET_SERVER_HOST}:"${JIANMU_TARGET_SERVER_DIR}"
        fi
else
     echo "${JIANMU_FILE_PATH}" does not exists!
fi

